package com.longshine.arthmetic.pattern.product_custom;

import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

public class ProductAndCustomerPattern {

	LinkedBlockingQueue<Integer> breads = new LinkedBlockingQueue<Integer>();
	private Object self = new Object();

	private int a = 0;
	private boolean isStart = true ;
	public void work() {
		new Thread(new Productor()).start();
		new Thread(new Customer()).start();
	}

	class Productor implements Runnable {
		public void run() {
			Random r = new Random();
			while (a++ <100) {
				synchronized (self) {
					if (breads.size() > 0) {
						try {
							self.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					int b = r.nextInt(100);
					if (b != 0) {
						breads.add(b);
						System.out.println("生产包子:" + b);
						self.notify();
					}
				}
			}
			isStart = false;
			System.out.println("停止生产包子");
		}
	}

	class Customer implements Runnable {
		public void run() {
			while (breads.size() > 0 || isStart) {
				synchronized (self) {
					if (breads.size() > 0) {
						int b = breads.poll();
						System.out.println("消费包子:" + b);
						if (b == 0) {
							break;
						}
						self.notify();
					} else {
						try {
							self.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
			System.out.println("停止消费包子");
		}
	}

	public static void main(String[] args) {
		new ProductAndCustomerPattern().work();
	}
}
